package post

import (
	"context"
	"time"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPostByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetPostByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostByIdLogic {
	return &GetPostByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetPostByIdLogic) GetPostById(req *types.IDReq) (*types.ForumPostInfoResp, error) {
	if req.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	data, err := l.svcCtx.ForumRpc.BackendGetPostById(l.ctx, &forumclient.PostIdReq{
		Id:        req.Id,
		WithMeta:  pointy.GetPointer(uint32(1)),
		WithMedia: pointy.GetPointer(uint32(1)),
		WithCard:  pointy.GetPointer(uint32(1)),
		WithTag:   pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		return nil, err
	}

	var parent *types.KBEntryInfo
	if data.ParentId != nil && *data.ParentId > 0 {
		res, err := l.svcCtx.BlogRpc.BackendGetKBPostById(l.ctx, &blogclient.KBPostIdReq{
			Id:        *data.ParentId,
			WithMeta:  pointy.GetPointer(uint32(1)),
			WithMedia: pointy.GetPointer(uint32(1)),
		})
		if err != nil {
			return nil, err
		}

		var media []*types.MediaInfo
		if len(res.Media) > 0 {
			for _, v := range res.Media {
				var url string
				if v.Url != nil && len(*v.Url) > 0 {
					url = *v.Url
				}
				if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
					url = *v.Uri
				}
				filename, mimeType, metaData := utils.ParseMetaData(v.MetaData)
				media = append(media, &types.MediaInfo{
					Uid:       v.Uid,
					Id:        v.Id,
					Thumbnail: v.Thumbnail,
					Order:     v.Order,
					Url:       pointy.GetPointer(url),
					Name:      pointy.GetPointer(filename),
					MimeType:  pointy.GetPointer(mimeType),
					AltText:   v.AltText,
					MetaData:  pointy.GetPointer(metaData),
				})
			}
		}

		parent = &types.KBEntryInfo{
			Title: res.Title,
			Slug:  res.Slug,
			Media: media,
		}
	}

	var meta []*types.MetaInfo
	if len(data.Meta) > 0 {
		for _, v := range data.Meta {
			meta = append(meta, &types.MetaInfo{
				Id:    v.Id,
				Key:   v.Key,
				Value: v.Value,
			})
		}
	}

	var media []*types.MediaInfo
	if len(data.Media) > 0 {
		for _, v := range data.Media {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
				url = *v.Uri
			}
			filename, mimeType, metaData := utils.ParseMetaData(v.MetaData)
			media = append(media, &types.MediaInfo{
				Uid:       v.Uid,
				Id:        v.Id,
				Thumbnail: v.Thumbnail,
				Order:     v.Order,
				Url:       pointy.GetPointer(url),
				Name:      pointy.GetPointer(filename),
				MimeType:  pointy.GetPointer(mimeType),
				AltText:   v.AltText,
				MetaData:  pointy.GetPointer(metaData),
			})
		}
	}

	var cards []*types.PostCardInfo
	if len(data.Cards) > 0 {
		for _, v := range data.Cards {
			cards = append(cards, &types.PostCardInfo{
				Uid:      v.Uid,
				Id:       v.Id,
				Type:     v.Type,
				LinkUrl:  v.LinkUrl,
				Title:    v.Title,
				PicUrl:   v.PicUrl,
				Subtitle: v.Subtitle,
				Label:    v.Label,
				Price:    v.Price,
			})
		}
	}

	var tags []*types.ForumTermInfo
	if len(data.Tags) > 0 {
		for _, v := range data.Tags {
			tags = append(tags, &types.ForumTermInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id: v.Id,
				},
				Name: v.Name,
				Slug: v.Slug,
			})
		}
	}

	author := &types.ForumAuthorInfo{
		Id:       data.AuthorId,
		Nickname: data.AuthorNickname,
		Avatar:   data.AuthorAvatar,
	}

	option := utils.GetAuditOptionByStatus(data.Status)

	return &types.ForumPostInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.ForumPostInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Title:         data.PostTitle,
			Content:       data.PostContentFiltered,
			ContentHtml:   data.PostContent,
			Excerpt:       data.PostExcerpt,
			AuthorId:      data.AuthorId,
			Status:        data.Status,
			CommentStatus: data.CommentStatus,
			Sort:          data.Sort,
			Sticky:        data.Sticky,
			CanStick:      option.CanStick,

			TopicId:    data.TopicId,
			ParentId:   data.ParentId,
			PhotoCount: data.PhotoCount,
			CreatedBy:  data.CreatedBy,
			CanSubmit:  option.CanSubmit,
			Loaded:     pointy.GetPointer(modelx.FormatTime(time.Now(), "")),

			Parent: parent,
			Meta:   meta,
			Media:  media,
			Card:   cards,
			Author: author,
			Tag:    tags,
		},
	}, nil
}
